package com.studentmanagement.ui;

import com.studentmanagement.model.User;
import com.studentmanagement.service.UserService;
import com.studentmanagement.util.IconUtil;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.FlatLightLaf;
import com.formdev.flatlaf.util.UIScale;

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.RoundRectangle2D;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JRadioButton studentRadio;
    private JRadioButton teacherRadio;
    private JRadioButton adminRadio;
    private ButtonGroup roleButtonGroup;
    private JButton loginButton;
    private JButton cancelButton;
    private JButton registerButton;

    private UserService userService;

    public LoginFrame() {
        userService = new UserService();
        initComponents();
        setupLayout();
        setupListeners();
    }

    private void initComponents() {
        setTitle("登录");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(450, 420);
        setLocationRelativeTo(null);
        setResizable(false);

        usernameField = new JTextField(20);
        passwordField = new JPasswordField(20);
        
        // 创建角色选择的单选按钮
        studentRadio = new JRadioButton("学生");
        teacherRadio = new JRadioButton("教师");
        adminRadio = new JRadioButton("管理员");
        
        // 添加到按钮组
        roleButtonGroup = new ButtonGroup();
        roleButtonGroup.add(studentRadio);
        roleButtonGroup.add(teacherRadio);
        roleButtonGroup.add(adminRadio);
        
        // 默认选中管理员
        adminRadio.setSelected(true);
        
        loginButton = new JButton("登录");
        cancelButton = new JButton("取消");
        registerButton = new JButton("注册账号");
    }

    private void setupLayout() {
        // Main wrapper panel
        JPanel wrapperPanel = new JPanel(new BorderLayout());
        wrapperPanel.setBackground(new Color(245, 245, 250));
        
        // Create header panel with gradient background
        JPanel headerPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                // Create a gradient from dark blue to lighter blue
                GradientPaint gp = new GradientPaint(
                    0, 0, new Color(41, 128, 185), 
                    0, getHeight(), new Color(52, 152, 219)
                );
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, getWidth(), getHeight());
                g2d.dispose();
            }
        };
        headerPanel.setPreferredSize(new Dimension(450, 80));
        headerPanel.setLayout(new BorderLayout());
        
        // Add title to header
        JLabel titleLabel = new JLabel("学生信息管理系统", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
        headerPanel.add(titleLabel, BorderLayout.CENTER);
        
        // Login Icon/Avatar
        JPanel avatarPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                // Draw avatar circle
                g2d.setColor(new Color(236, 240, 241));
                int diameter = 80;
                int x = (getWidth() - diameter) / 2;
                int y = 0;
                g2d.fillOval(x, y, diameter, diameter);
                
                // Draw person icon
                g2d.setColor(new Color(189, 195, 199));
                int headSize = 30;
                int headX = getWidth() / 2 - headSize / 2;
                int headY = y + 15;
                g2d.fillOval(headX, headY, headSize, headSize);
                
                // Draw body
                int bodyWidth = 40;
                int bodyHeight = 30;
                int bodyX = getWidth() / 2 - bodyWidth / 2;
                int bodyY = headY + headSize - 5;
                g2d.fillArc(bodyX, bodyY, bodyWidth, bodyHeight, 0, 180);
                
                g2d.dispose();
            }
        };
        avatarPanel.setPreferredSize(new Dimension(450, 40));
        avatarPanel.setOpaque(false);
        
        // Main content panel
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBackground(new Color(245, 245, 250));
        contentPanel.setBorder(new EmptyBorder(50, 30, 20, 30));
        
        // Form panel with fields
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(7, 7, 7, 7);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // Style text fields
        usernameField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请输入用户名");
        usernameField.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_ICON, IconUtil.getUserIcon());
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameField.setPreferredSize(new Dimension(200, 36));
        
        passwordField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请输入密码");
        passwordField.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_ICON, IconUtil.getLockIcon());
        passwordField.putClientProperty(FlatClientProperties.STYLE, "showRevealButton: true");
        passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        passwordField.setPreferredSize(new Dimension(200, 36));
        
        // 样式化单选按钮
        Font radioFont = new Font("微软雅黑", Font.PLAIN, 14);
        studentRadio.setFont(radioFont);
        teacherRadio.setFont(radioFont);
        adminRadio.setFont(radioFont);
        
        studentRadio.setOpaque(false);
        teacherRadio.setOpaque(false);
        adminRadio.setOpaque(false);
        
        // 创建角色选择面板
        JPanel rolePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 5));
        rolePanel.setOpaque(false);
        rolePanel.add(studentRadio);
        rolePanel.add(teacherRadio);
        rolePanel.add(adminRadio);
        
        // 为角色面板添加一个标题边框
        rolePanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(new Color(220, 220, 220), 1, true),
            "请选择角色",
            TitledBorder.LEADING,
            TitledBorder.TOP,
            new Font("微软雅黑", Font.PLAIN, 12),
            new Color(120, 120, 120)
        ));
        
        // Add components to form panel
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        formPanel.add(usernameField, gbc);
        
        gbc.gridy = 1;
        formPanel.add(passwordField, gbc);
        
        gbc.gridy = 2;
        formPanel.add(rolePanel, gbc);
        
        // Buttons panel
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setOpaque(false);
        
        // Style buttons
        loginButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        loginButton.setBackground(new Color(52, 152, 219));
        loginButton.setForeground(Color.WHITE);
        loginButton.putClientProperty(FlatClientProperties.STYLE, "arc: 10");
        loginButton.setPreferredSize(new Dimension(100, 36));
        loginButton.setFocusPainted(false);
        
        registerButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        registerButton.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_BORDERLESS);
        registerButton.setForeground(new Color(52, 152, 219));
        
        cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        cancelButton.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_BORDERLESS);
        cancelButton.setForeground(new Color(149, 165, 166));
        
        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);
        buttonPanel.add(cancelButton);
        
        // Assemble the content panel
        contentPanel.add(formPanel, BorderLayout.CENTER);
        contentPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // Add all panels to main wrapper
        wrapperPanel.add(headerPanel, BorderLayout.NORTH);
        wrapperPanel.add(avatarPanel, BorderLayout.CENTER);
        wrapperPanel.add(contentPanel, BorderLayout.SOUTH);
        
        // Add wrapper to frame
        setContentPane(wrapperPanel);
    }

    private void setupListeners() {
        loginButton.addActionListener(this::performLogin);
        cancelButton.addActionListener(e -> System.exit(0));
        registerButton.addActionListener(this::openRegistrationDialog);
    }

    private void performLogin(ActionEvent e) {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        User.UserRole selectedRole = getSelectedRole();

        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空。", 
                                            "登录错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        User user = userService.login(username, password);

        if (user != null && user.getRole() == selectedRole) {
            JOptionPane.showMessageDialog(this, "登录成功！欢迎您，" + user.getUsername(),
                                            "登录成功", JOptionPane.INFORMATION_MESSAGE);
            openMainWindow(user);
            dispose(); 
        } else {
            JOptionPane.showMessageDialog(this, "用户名、密码或角色无效。",
                                            "登录失败", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private User.UserRole getSelectedRole() {
        if (studentRadio.isSelected()) {
            return User.UserRole.STUDENT;
        } else if (teacherRadio.isSelected()) {
            return User.UserRole.TEACHER;
        } else if (adminRadio.isSelected()) {
            return User.UserRole.ADMIN;
        }
        return User.UserRole.STUDENT; // 默认
    }
    
    private void openMainWindow(User user) {
        System.out.println("正在为用户打开主窗口: " + user.getUsername() + "，角色: " + user.getRole());
        MainFrame mainFrame = new MainFrame(user);
        mainFrame.setVisible(true);
    }

    private void openRegistrationDialog(ActionEvent e) {
        RegistrationDialog registrationDialog = new RegistrationDialog(this);
        registrationDialog.setVisible(true);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                // 设置 FlatLaf 主题
                FlatLightLaf.setup();
            } catch (Exception ex) {
                System.err.println("初始化 FlatLaf 失败: " + ex.getMessage());
            }
            LoginFrame loginFrame = new LoginFrame();
            loginFrame.setVisible(true);
        });
    }
}